﻿/**
 * Copyright (C) 2011 original author and authors
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NGuice.Inject.Matcher;
using NGuice.Inject.Internal.Util;

namespace NGuice.Inject.Spi
{
    //complete!
    /// <summary>
    /// 绑定一个类型（使用匹配器）到一个给定类型的监听器。注册将在模型中使用Binder.BindListener(Matcher, TypeListener)显式创建：
    /// <code>
    /// Register(Only(PaymentService &ltCreditCard&gt, listener);
    /// </code>
    /// </summary>
    public sealed class TypeListenerBinding : IElement
    {
        private readonly object source;

        private readonly IMatcher typeMatcher;//必须为泛型参数，泛型参数必须为Type的超类

        private readonly ITypeListener listener;

        /// <summary>
        /// 必须为泛型参数，泛型参数必须为Type的超类
        /// </summary>
        /// <param name="source"></param>
        /// <param name="listener"></param>
        /// <param name="typeMatcher"></param>
        public TypeListenerBinding(object source, ITypeListener listener, IMatcher typeMatcher)
        {
            Preconditions.CheckSuperGenericParameter<Type>(typeMatcher);
            this.source = source;
            this.listener = listener;
            this.typeMatcher = typeMatcher;
        }

        public ITypeListener Listener
        {
            get
            {
                return listener;
            }
        }

        /// <summary>
        /// 获取用于选择哪一个类型监听器应该被通知的类型匹配器
        /// </summary>
        public IMatcher TypeMatcher
        {
            get
            {
                return typeMatcher;
            }
        }

        public object Source
        {
            get
            {
                return source;
            }
        }

        public T AcceptVisitor<T>(IElementVisitor<T> visitor)
        {
            return visitor.Visit(this);
        }

        public void ApplyTo(IBinder binder)
        {
            binder.WithSource(Source).BindListener(typeMatcher, listener);
        }
    }
}
